package com.appointment.advice;

import com.appointment.exception.FrontEndException;
import com.appointment.result.R;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

@RestControllerAdvice
@Slf4j
public class GlobalAdvice {
    @ExceptionHandler(IllegalArgumentException.class)
    public R<Object> illegalArgumentException(HttpServletResponse response, IllegalArgumentException e) {
        log.warn("参数错误: {}", e.getLocalizedMessage());
        // 设置状态码为500
        response.setStatus(500);
        return R.error("服务器异常，请稍后再试！");
    }

    @ExceptionHandler(Exception.class)
    public R<Object> exception(HttpServletResponse response, Exception e) {
        log.error("发生异常: {}", e.getLocalizedMessage());
        // 设置状态码为500
        response.setStatus(500);
        return R.error("服务器异常，请稍后再试！");
    }

    @ExceptionHandler(FrontEndException.class)
    public R<Object> frontEndException(FrontEndException e) {
        log.error("由于前台传输数据，发生异常: {}", e.getLocalizedMessage());
        return R.error(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<Object> methodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("参数校验异常: {}", e.getLocalizedMessage());
        return R.error(Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage());
    }
}
